package com.demo;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import java.util.List;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.Deployment;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.alibaba.fastjson.JSONObject;


/**
 * 
 * 用户、组 和任务 
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Process01 {
	
	@Autowired
	IdentityService identityService;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    RepositoryService repositoryService;
    @Autowired
    TaskService taskService;
    @Autowired
    HistoryService historyService;
    
	@Before
	public void setUp() {
    	// 创建用户
    	User user  = identityService.newUser("NellJin");
    	user.setFirstName("Nell");
    	user.setLastName("Jin");
    	user.setEmail("nelljin@sh.cn");
    	// 保存到数据库
    	identityService.saveUser(user);
    
    	Group group = identityService.newGroup("deptLeader");
    	group.setName("部门领导");
    	group.setType("assignment");
    	identityService.saveGroup(group);
    	
    	// 用户加入到组里
    	identityService.createMembership("NellJin", "deptLeader");
    	
	}

    @After
    public void afterInvoketestMethod() {
    	identityService.deleteMembership("NellJin", "deptLeader");
    	identityService.deleteGroup("deptLeader");
    	identityService.deleteUser("NellJin");
    }

	// 部署流程
    @Test
    public void deployment() {
    	String bpmnFileName = "processes/Process01.bpmn";
        repositoryService.createDeployment().addClasspathResource(bpmnFileName).deploy();
        ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionKey("process01").singleResult();
    	assertEquals("process01", pd.getKey());
    }
    
    @Test
    public void testUserAndGroupInUserTask() {
    	ProcessInstance pi = runtimeService.startProcessInstanceByKey("process01");
    	assertNotNull(pi);
    	List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("deptLeader").list();
    	for (Task task : tasks) {
			taskService.claim(task.getId(), "NellJin");
			taskService.complete(task.getId());
		}
    	assertNotNull(tasks);
    }
    
}
